//添加无效方法 加强版（方法体是 多行废代码） -----------------

const LINENUM = 8;
const LINENUM_RADOM = 20;
const rateConfig = [[.2, .6],[.3, .7], [.4, .8], [.5, .9]];//混淆强度
var RATE = [0,0];

var fs = require('fs');
var path = require('path');

var classExpString = "Xxxx";
var funString;


//node addcode.js /Users/zhixiang/Documents/proj/minigame-btxd/client_btxd_z/build/wechatgame/src/project.41ad2.js 'BaoShi' 4
var arguments = process.argv.splice(2);

classExpString = arguments[1];
///funString = '(){';
funString = '= function(){';
var strong = arguments[2]; //取值1-4
if(strong <1 || strong > 4) strong = 3;
RATE = rateConfig[strong-1];

var jsurl = arguments[0];
jsJiaMiFun(jsurl);

function jsJiaMiFun(phppath){

	console.log("执行文件：" + phppath);
	let codeContent = fs.readFileSync(phppath, { encoding: "utf8" });
	//console.log(codeContent);

	/** 格式化代码 ******************/
	var js_parse = require("./js_parse.js");
	codeContent = js_parse.js_beautify(codeContent, 4, ' ');


	//====增加干扰代码 插入一个类真实的方法 代码 ==================================================================
	let arr2 = codeContent.split("\n");
	//console.log(arr2.length, arr2);

	let rate = RATE[0] || 0.3;
	for(var i=LINENUM; i<arr2.length - 1; i++){

		let formatStr = Trim(arr2[i], "g"); //当前行
		//arr2[i] = String(arr2[i]);
		let formatStr2 = Trim(arr2[i-1], "g"); //上一行
		//arr2[i-1] = String(arr2[i-1]);
		let formatStr3 = Trim(arr2[i+1], "g"); //下一行
		//arr2[i+1] = String(arr2[i+1]);

		let canInsert = false;
		//【修改代码】
		///let isFun = (arr2[i].indexOf("           ") !=-1 ) && arr2[i].indexOf("(") !=-1 && arr2[i].indexOf(") {") !=-1; //用这种方法来判断是类方法
		let isFun = (arr2[i].indexOf(".prototype.") !=-1 ) && arr2[i].indexOf("= function(") !=-1;
		var str = '';
		///if(isFun && formatStr2 == "}"){
		if(isFun && formatStr2 == "},"){
			canInsert = Math.random() < rate;
			var classStr = formatStr.split(".")[0];
			if(canInsert  && classStr !='cc'){
				///str = getAddSpace(arr2[i]) + '            get' + getRadomStr(4, 1) + funString + getRadomStr2() + ' }';
				str = getAddSpace(arr2[i]) + classStr + '.prototype.set' + getRadomStr(4, 1) + funString + getRadomStr2() + '},';
				// console.log(str)
				arr2.splice(i,0,str);
			}
		}
		else{
			///isFun = (arr2[i+1].indexOf("           ") !=-1 ) && formatStr3.indexOf("(") !=-1 && arr2[i].indexOf(") {") !=-1;
			isFun = (arr2[i+1].indexOf(".prototype.") !=-1 ) && formatStr3.indexOf("= function(") !=-1;
			if(formatStr == "}," && isFun) {
				canInsert = Math.random() < rate;
				var classStr = formatStr3.split(".")[0];
				if(canInsert && classStr !='cc'){
					///str = getAddSpace(arr2[i+1])  + '            get' + getRadomStr(4, 1) + funString + getRadomStr2() + ' }';
					var funname = getRadomStr(4, 1);
					str = getAddSpace(arr2[i]) + classStr + '.prototype.set' + funname + funString + getRadomStr2() +
					";this.set" + funname + "();" + '},';
					arr2.splice(i,0,str);
				}
			}
		}
	}

	codeContent = arr2.join("\n");
	//console.log(codeContent);
	
	/** 压缩代码 ******************/
	codeContent = js_parse.jsmin("", codeContent, 2);

    fs.writeFileSync(phppath, codeContent, { encoding: "utf8" });
    console.log("执行完成！--" + phppath);
}

function getLeftSpace(str){
	if(!str) return 0;
	let num = str.length - lTrim(str).length;
	return num;
}

function getAddSpace(str){
	if(!str) return "";
	let num = str.length - lTrim(str).length;
	let formatStr = Trim(str, "g");
	if(formatStr == "}")
		num += 4;
	let space = "";
	while(num > 0){
		space += " ";
		num--;
	}
	return space;
}
function getRadomStr(len, type){
	var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
	if(type == 1) $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz'; //非数字
	var maxPos = $chars.length;
	var pwd = '';
	for (var i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}
function Trim(str, is_global) {
	//console.log("==", str)
	str = String(str);
	var result;
	result = str.replace(/(^\s+)|(\s+$)/g,"");
	if(is_global && is_global.toLowerCase()=="g"){
		result = result.replace(/\s/g,"");
	}
	return result;
}
function lTrim(str) {
	str = String(str);
	var result = str.replace(/(^\s+)/g,"");
	return result;
}

function getRadomStr2(){
	//【增加代码】
	let list = [
		`var seats = [];
		var selected_seatssss = Array.prototype.slice.call(document.querySelectorAll(".row .seat.selected"));
		var seatsIndex = selected_seatssss.map(function(seat) {
		  return Array.prototype.indexOf.call(seats, seat);
		});
		localStorage.setItem("selected_seatssss", JSON.stringify(seatsIndex));
		
		var selected_seatssssCount = selected_seatssss.length;
		var innerText = selected_seatssssCount;
		
		function replaceString(str, isGlobal) {
		  var result = str.replace(/(^\s+)|(\s+$)/g, "");
		  if (isGlobal && isGlobal.toLowerCase() === "g") {
			result = result.replace(/\s/g, "");
		  }
		  return result;
		}`,

		`var r, start_trom, angleaa, colorss, alphaaa, shapeqq, stop_clean;
        var x = 0;        `,

		`var r, start_trom, angle, colorss, alphaaa, shapeqq, stop_clean;        `,

		`var str, split;
        if(!str){
            return [];
        }
        var list = String(str).split(split);
        var newList = [];
        for(var i=0; i<list.length; i++){
            newList[i] = Number(list[i]);
        }
        return newList;`,

		`var day,hour;var s = "";    s+=day;    return s;`,
		
		`var str,len;
        if(!str || str.length <= len) 
            return str;
        let len2 = len*2;
        for(var i=len;i<=str.length;i++)
        {
            var rs = str.substr(0,i);
            if(res > len2)
                return   str.substr(0,i-1);
        }
        return str;`,
		
		`var rota;while(rota < 0)
			rota += 360;
		while(rota > 360)
			rota -= 360;
		return rota;`,
		
		`var p1,p2;var xx = Math.abs(p1.x - p2.x);
		var yy = Math.abs(p1.y - p2.y);
		return Math.pow(xx*xx + yy*yy,0.5)`,
		
		`var str;var arr = this.split(str);
		for(var i=0;i<arr.length;i++)
		{
			var temp = arr[i].split(':');
			arr[i] = {
				id:parseInt(temp[0]),
				num:parseInt(temp[1]),
			}
		}
		return arr;`,
		
		`var list;
		if(!list) return;
		list.dataProvider = null;
		//必现调用下面2句，并且 需要在hide之前调用
		list.dataProviderRefreshed();
		list.validateNow();`,
		
		`var str,v,length;
		if(typeof v == 'string')
			str = v;
		else
        	str = v.toFixed(length);
		var char = str.charAt(str.length-1);
		while(char == '0' || char == '.')
		{
			str = str.substr(0,str.length - 1);
			if(char == '.')
			     break;
			char = str.charAt(str.length-1);
		}
		return str`,
		
		`var data;
		if(!data)
			return null;
		var oo = {};
		var arr = data.split(',');
		for(var i=0;i<arr.length;i++)
		{
			var temp = arr[i].split(':');
			oo[temp[0].toLowerCase()] = parseFloat(temp[1]);
		}
		return oo;`,
		
		`return (234 + '').replace(/[^\x00-\xff]/g,"aa").length;`
	];
	var codeArray = [
		`
		var seats = [];
		var selected_seatssss = Array.prototype.slice.call(document.querySelectorAll(".row .seat.selected"));
		var seatsIndex = selected_seatssss.map(function(seat) {
		  return Array.prototype.indexOf.call(seats, seat);
		});
		localStorage.setItem("selected_seatssss", JSON.stringify(seatsIndex));
		var selected_seatssssCount = selected_seatssss.length;
		var innerText = selected_seatssssCount;
		function replaceString(str, isGlobal) {
		  var result = str.replace(/(^\s+)|(\s+$)/g, "");
		  if (isGlobal && isGlobal.toLowerCase() === "g") {
			result = result.replace(/\s/g, "");
		  }
		  return result;
		}
		`,
	  
		`
		var r, start_trom, angleaa, colorss, alphaaa, shapeqq, stop_clean;
		var x = 0;
		`,
	  
		`
		var r, start_trom, angle, colorss, alphaaa, shapeqq, stop_clean;
		`,
	  
		`
		var str, split;
		if (!str) {
		  return [];
		}
		var list = String(str).split(split);
		var newList = [];
		for (var i = 0; i < list.length; i++) {
		  newList[i] = Number(list[i]);
		}
		return newList;
		`,
	  
		`
		var day, hour;
		var s = "";
		s += day;
		return s;
		`,
	  
		`
		var str, len;
		if (!str || str.length <= len) {
		  return str;
		}
		var len2 = len * 2;
		for (var i = len; i <= str.length; i++) {
		  var rs = str.substr(0, i);
		  if (res > len2) {
			return str.substr(0, i - 1);
		  }
		}
		return str;
		`,
	  
		`
		var rota;
		while (rota < 0) {
		  rota += 360;
		}
		while (rota > 360) {
		  rota -= 360;
		}
		return rota;
		`,
	  
		`
		var p1, p2;
		var xx = Math.abs(p1.x - p2.x);
		var yy = Math.abs(p1.y - p2.y);
		return Math.pow(xx * xx + yy * yy, 0.5);
		`,
	  
		`
		var str;
		var arr = this.split(str);
		for (var i = 0; i < arr.length; i++) {
		  var temp = arr[i].split(':');
		  arr[i] = {
			id: parseInt(temp[0]),
			num: parseInt(temp[1]),
		  };
		}
		return arr;
		`,
	  
		`
		var list;
		if (!list) {
		  return;
		}
		list.dataProvider = null;
		// 必现调用下面2句，并且 需要在hide之前调用
		list.dataProviderRefreshed();
		list.validateNow();
		`,
	  
		`
		var str, v, length;
		if (typeof v == 'string') {
		  str = v;
		} else {
		  str = v.toFixed(length);
		}
		var char = str.charAt(str.length - 1);
		while (char == '0' || char == '.') {
		  str = str.substr(0, str.length - 1);
		  if (char == '.') {
			break;
		  }
		  char = str.charAt(str.length - 1);
		}
		return str;
		`,
	  
		`
		var data;
		if (!data) {
		  return null;
		}
		var oo = {};
		var arr = data.split(',');
		for (var i = 0; i < arr.length; i++) {
		  var temp = arr[i].split(':');
		  oo[temp[0].toLowerCase()] = parseFloat(temp[1]);
		}
		return oo;
		`,
	  
		`
		return (234 + '').replace(/[^\x00-\xff]/g, "aa").length;
		`
	  ];
	return codeArray[Math.floor(codeArray.length * Math.random())];
}